package org.railage.client.filters;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.railage.client.beans.AuthBean;
import org.railage.common.dto.UserDTO;

/**
 * Servlet Filter implementation class RootIndexFilter
 */
@WebFilter("/index.xhtml")
public class RootIndexFilter implements Filter {
	
	public static final String AUTH_PATH = "/railage-web/auth.xhtml";

    /**
     * Default constructor. 
     */
    public RootIndexFilter() {

    }

	/**
	 * @see Filter#destroy()
	 */
	public void destroy() {

	}

	/**
	 * @see Filter#doFilter(ServletRequest, ServletResponse, FilterChain)
	 */
	public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws IOException, ServletException {

		HttpServletRequest httpReq = (HttpServletRequest) req;
		HttpServletResponse httpResp = (HttpServletResponse) resp;
		
		UserDTO user = (UserDTO) httpReq.getSession().getAttribute(AuthBean.SESSION_USER_PARAM);
		
		if (user == null) {
			httpResp.sendRedirect(AUTH_PATH);
		} else {
			int role = user.getRole();
			if (role == 0) {
				httpResp.sendRedirect("/railage-web/client/");
			} else if (role == 1) {
				httpResp.sendRedirect("/railage-web/manager/");
			}
		}
	}

	/**
	 * @see Filter#init(FilterConfig)
	 */
	public void init(FilterConfig fConfig) throws ServletException {

	}

}
